package com.atguigu.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author: 绝城孤影
 * @Date: 2024/10/13 22:41
 * @Version: v1.0.0
 * @Description: MP自动填充拦截处理器
 **/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
	@Override
	public void insertFill(MetaObject metaObject) {
		log.info(" -- start insert fill ...");
		// param1: 元对象; param2:需设置的字段; param3:设置类型; param4: 设置数据
		this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now().minusHours(2));
		this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now().minusHours(1));

		// 判断age是否赋值
		Object age = this.getFieldValByName("age", metaObject);
		if(age == null){
			log.info("start insert fill age....");
			this.strictInsertFill(metaObject, "age", String.class, "18");
		}

		// 判断是否具备属性再设置
		boolean hasAuthor = metaObject.hasSetter("author");
		if(hasAuthor) {
			log.info("start insert fill author...");
			this.strictInsertFill(metaObject, "author", String.class, "Helen");
		}
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		log.info("start update fill ....");
		this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
	}
}
